<template>
  <el-dialog :title="title ? '新增' : '修改'" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="dataForm.type">
          <el-radio v-for="(type, index) in dataForm.typeList" :label="index" :key="index">{{ type }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="dataForm.typeList[dataForm.type] + '名称'" prop="name">
        <el-input v-model="dataForm.name" :placeholder="dataForm.typeList[dataForm.type] + '名称'"></el-input>
      </el-form-item>
      <el-form-item label="上级菜单" prop="parentName">
        <el-popover
            ref="menuListPopover"
            placement="bottom-start"
            :disabled="disable"
            trigger="click">
          <el-tree
              :data="menuTreeData"
              :props="menuTreeProps"
              node-key="menuId"
              ref="menuListTree"
              :default-expanded-keys="expandedKey"
              @node-click="handleNodeClick"
              :highlight-current="true"
              :expand-on-click-node="false">
          </el-tree>
          <el-input
              v-model="dataForm.parentName"
              v-popover:menuListPopover
              :readonly="true"
              placeholder="点击选择上级菜单"
              class="menu-list__input" slot="reference">
          </el-input>
        </el-popover>
      </el-form-item>
      <el-form-item v-if="dataForm.type === 1" label="页面路径" prop="url">
        <el-input v-model="dataForm.url" placeholder="页面路径">
          <template slot="prepend">src/views</template>
          <template slot="append">.vue</template>
        </el-input>

      </el-form-item>
      <el-form-item v-if="dataForm.type === 2" label="授权标识" prop="perms">
        <el-input v-model="dataForm.permission" placeholder="多个用逗号分隔, 如: user:list,user:create"></el-input>
      </el-form-item>
      <el-form-item label="排序号" prop="orderNum">
        <el-input-number v-model="dataForm.orderNum" controls-position="right" :min="0" label="排序号"></el-input-number>
      </el-form-item>
      <el-form-item label="菜单图标" >
        <el-popover
            placement="bottom-start"
            width="460"
            trigger="click"
            @show="$refs['iconSelect'].reset()">
          <IconSelect ref="iconSelect" @selected="handleIconSelected"/>
          <el-input slot="reference" v-model="dataForm.icon" placeholder="点击选择图标">
            <svg-icon
                v-if="dataForm.icon"
                slot="prefix"
                :icon-class="dataForm.icon"
                class="el-input__icon"
                style="height: 40px;width: 16px; "/>
            <i v-else slot="prefix" class="el-icon-search el-input__icon"/>
          </el-input>
        </el-popover>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submitDialogForm('dataForm')">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {select, addMenu, menuDetail, updateMenu} from '@/api/system/menu'
import IconSelect from '@/components/IconSelect'

export default {
  name: "menu-add-or-update",
  components: {IconSelect},
  data() {
    let validateUrl = (rule, value, callback) => {
      if (this.dataForm.type === 1 && !/\S/.test(value)) {
        callback(new Error('页面路径不能为空'))
      } else {
        callback()
      }
    }
    return {
      title: true,
      disable: false,
      visible: false,
      iconList: [],
      dataForm: {
        menuId: 0,
        type: 1,
        typeList: ['目录', '菜单', '按钮'],
        name: '',
        parentId: 0,
        parentName: '',
        url: '',
        orderNum: 0,
        icon: '',
        permission: ''
      },
      dataRule: {
        name: [
          {required: true, message: '菜单名称不能为空', trigger: 'blur'}
        ],
        parentName: [
          {required: true, message: '上级菜单不能为空', trigger: 'change'}
        ],
        url: [
          {required: true, validator: validateUrl, trigger: 'blur'}
        ]
      },
      menuTreeData: [],
      menuTreeProps: {
        children: 'children',
        label: 'name'
      },
      //展开节点
      expandedKey: [],
      //添加或修改判断标志 true:添加  false:修改
      addUpdateFlag: false
    };
  },
  methods: {
    init(row, flag) {
      this.dataForm.menuId = row == undefined ? undefined : row.menuId
      select().then(res => {
        if (res.status) {
          this.menuTreeData = res.data
        }
      }).then(() => {
        this.$nextTick(() => {
          this.disable = false
          this.expandedKey = []
          this.dataForm.permission = ''
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        if (flag) {//新增
          this.dataForm.url = '';
          this.dataForm.parentId = row.menuId;
          this.dataForm.parentName = row.name;
          this.disable = true;
          this.addUpdateFlag = true;
        } else {
          if (this.dataForm.menuId) {  //修改
            this.title = false;
            this.addUpdateFlag = false;
            menuDetail(this.dataForm.menuId).then(res => {
              if (res.status) {
                const menu = res.data;
                this.expandedKey.push(menu.menuId);
                this.dataForm.menuId = menu.menuId;
                this.dataForm.icon = menu.icon;
                this.dataForm.name = menu.name;
                this.dataForm.orderNum = menu.orderNum;
                this.dataForm.type = menu.type;
                this.dataForm.url = menu.url;
                this.dataForm.parentName = menu.parentName || '一级菜单';
                this.dataForm.parentId = menu.parentId;
                this.dataForm.permission = menu.permission;
              }
            });
          } else { //新增
            this.dataForm.url = '';
            this.addUpdateFlag = true;
          }
        }
      })
      this.visible = true
    },
    handleNodeClick(data) {
      this.dataForm.parentId = data.menuId
      this.dataForm.parentName = data.name
    },
    submitDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //url 若没有'/' 开始，添加上
          let url = this.dataForm.url;
          let firstUrl = url.substring(0,1);
          if (url.length > 0 && firstUrl != '/') {
            this.dataForm.url = '/' + url;
          }
          if (this.addUpdateFlag) { //新增导航菜单
            addMenu(this.dataForm).then(res => {
              if (res.status) {
                let message = this.dataForm.typeList[this.dataForm.type]
                this.$message.success(`新增${message}成功`);
                this.visible = false
                this.$emit('refreshDataList','true')
              } else {
                this.$message.error(res.msg)
              }
            })
          } else { //修改导航菜单
            //改为目录,url置空
            if (this.dataForm.type == 0) {
              this.dataForm.url = ''
            }
            updateMenu(this.dataForm).then(res => {
              if (res.status) {
                this.$message.success("修改菜单成功")
                this.visible = false
                this.$emit('refreshDataList','true')
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleIconSelected(name) {
      this.dataForm.icon = name
    }
  },
}
</script>

<style lang="scss" scoped>
.mod-menu {
  .menu-list__input,
  .icon-list__input {
    > .el-input__inner {
      cursor: pointer;
    }
  }

  &__icon-popover {
    width: 458px;
    overflow: hidden;
  }

  &__icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }

  &__icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;

    > .el-button {
      padding: 8px;
      margin: 8px 0 0 8px;

      > span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }

  .icon-list__tips {
    font-size: 18px;
    text-align: center;
    color: #e6a23c;
    cursor: pointer;
  }
}
</style>
